<template>
  <div>
    <el-form ref="pram" :model="pram" :rules="rules" label-width="80px" @submit.native.prevent>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="first">
          <el-form-item label="标题" prop="title">
            <el-input v-model="pram.title" maxlength="150" placeholder="标题" />
          </el-form-item>
          <el-form-item label="分类" prop="type">
            <el-select v-model="pram.type" placeholder="分类" clearable style="width: 100%">
              <el-option
                v-for="(item,index) in typeList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="封面图" prop="coverImage">
            <el-tooltip
              class="item"
              effect="dark"
              content="上传图片"
              placement="top-start"
            >
              <el-upload
                class="upload-demo"
                action
                accept="image/gif,image/jpeg,image/png"
                :before-upload="onBeforeUpload"
                :http-request="handleUploadForm"
                :on-change="imgSaveToUrl"
                :headers="myHeaders"
                :show-file-list="false"
              >
                <el-button
                  icon="el-icon-plus"
                  class="mr15 definedArea"
                  style="width:80px;height:80px;"
                ></el-button>
              </el-upload>
            </el-tooltip>
            <div v-if="this.dialogImageUrl">
              <el-button
                icon="el-icon-close"
                class="imgDel"
                @click.native="handlerImgDel"
              ></el-button>
              <img width="100%" :src="this.dialogImageUrl" alt="" class="img-box">
            </div>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch v-model="pram.status" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="内容" name="second">
          <el-form-item prop="content" class="rich-content">
            <Tinymce v-model="pram.content"></Tinymce>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
<!--      <el-form-item label="排序">-->
<!--        <el-input-number v-model="pram.sort" :min="0"/>-->
<!--      </el-form-item>-->
    </el-form>
    <div class="btn-box">
      <el-button type="primary" @click="handlerSubmit('pram')" v-hasPermi="['admin:study:update','admin:study:save']">{{ isCreate===0?'确定':'更新' }}</el-button>
      <el-button @click="close">取消</el-button>
    </div>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce/index'
import * as studyApi from '@/api/study.js'
import * as systemSetting from '@/api/systemSetting.js'
import {getToken} from "@/utils/auth";
import {Debounce} from '@/utils/validate'
import Templates from "../appSetting/wxAccount/wxTemplate/index";
export default {
  // name: "edit"
  components: { Templates, Tinymce},
  props: {
    isCreate: {
      type: Number,
      required: true
    },
    editData: {
      type: Object,
      default: () => {
        return { rules: [] }
      }
    },
    allTypeList: {
      type: Array
    },
  },
  data() {
    return {
      constants:this.$constants,
      activeName:"first",
      otherInfoVisible: false,
      pram: {
        title: null,
        type:null,
        content:null,
        coverImage:null,
        //sort: 0,
        status:1,
        id: 0,
      },
      rules: {
        title: [{ required: true, message: '请填文章名称', trigger: ['blur', 'change'] }],
        type: [{ required: true, message: '请选择分类', trigger: ['blur', 'change'] }],
        content: [{ required: true, message: '请填文章内容', trigger: ['blur'] }],
        coverImage: [{ required: true, message: '请上传封面图', trigger: ['blur', 'change'] }],
      },
      myHeaders: { "X-Token": getToken() },
      localFile: null,
      dialogImageUrl: null,

      typeList:[],
    }
  },
  mounted() {
    this.initEditData()
  },
  methods: {
    close() {
      this.$emit('hideEditDialog')
    },
    handleClick(tab) {
      if (tab.name === 'second') {
        this.otherInfoVisible = true;
      }else{
        this.otherInfoVisible = false;
      }
    },

    //图片上传有关
    onBeforeUpload(file) {
      const isIMAGE = file.type === 'image/jpg'||'image/gif'||'image/png';
      const isLt1M = file.size / 1024 / 1024 < 10;

      if (!isIMAGE) {
        this.$message.error('上传文件只能是jpg、png或gif格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isIMAGE && isLt1M;
    },
    // 上传
    handleUploadForm(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      systemSetting.fileImageApi(formData).then((res) => {
        //图片上传接口 后期调用
        this.pram.coverImage = res

        loading.close();
        this.$message.success("上传成功");
        })
      .catch((res) => {
        loading.close();
      });
    },
    // 选取图片后自动回调，里面可以获取到文件
    imgSaveToUrl(event) {
      // 也可以用file
      this.localFile = event.raw; // 或者 this.localFile=file.raw

      // 转换操作可以不放到这个函数里面，
      // 因为这个函数会被多次触发，上传时触发，上传成功也触发
      let reader = new FileReader();
      reader.readAsDataURL(this.localFile); // 这里也可以直接写参数event.raw

      // 转换成功后的操作，reader.result即为转换后的DataURL ，
      // 它不需要自己定义，你可以console.integralLog(reader.result)看一下
      reader.onload = () => {
        //console.integralLog(reader.result)
      };

      /* 另外一种本地预览方法 */

      let URL = window.URL || window.webkitURL;
      this.dialogImageUrl = URL.createObjectURL(event.raw);
      // 转换后的地址为 blob:http://xxx/7bf54338-74bb-47b9-9a7f-7a7093c716b5
    },
    handlerImgDel(){
      this.pram.coverImage = null
      this.dialogImageUrl = null
    },

    initEditData() {
      this.typeList = this.allTypeList

      if (this.isCreate !== 1) return //编辑
      const { title, type, content, coverImage, status, id } = this.editData //通过list中slot-scope=“scope“，scope.$index就是该行的下标，scope.row就是该行的数据所有消息对象，有了这两个参数就可以实现编辑、删除功能（this.editData就是scope.row传入的对象参数）
      this.pram.title = title
      this.pram.type = type
      this.pram.content = content
      this.pram.coverImage = coverImage
      this.dialogImageUrl = coverImage
      this.pram.status = status
      //this.pram.sort = sort
      this.pram.id = id
    },

    handlerSubmit:Debounce(function(form) {
      this.$refs[form].validate(valid => {
        if (!valid){
          setTimeout(() => {
            //使用定时器，防止出发此处判断__error时验证器的__error的class还未添加
            //console.log(document.getElementsByClassName('el-form-item__error').length)
            if (document.getElementsByClassName('el-form-item__error').length > 0) {
              let errorNode = document.getElementsByClassName('is-error')[0];//$('.is-error')
              //console.log(errorNode.parentNode.id)
              //如果html结构变了此处需要检查是否多级parentNode
              if (errorNode.parentNode.id === "pane-second") {
                this.activeName = "second"
                this.otherInfoVisible = true
              } else if (errorNode.parentNode.id === "pane-first") {
                this.activeName = "first"
                this.otherInfoVisible = false
              }
            }
          }, 200);
          return
        }
        if (this.isCreate === 0) {
          this.handlerSave()
        } else {
          this.handlerEdit()
        }
      })
    }),
    handlerSave() {
      studyApi.doAdd(this.pram).then(data => {
        this.$message.success('创建学习文章成功')
        this.$emit('hideEditDialog')
      })
    },
    handlerEdit() {
      studyApi.doAdd(this.pram).then(data => {
        this.$message.success('更新学习文章成功')
        this.$emit('hideEditDialog')
      })
    },
  }
}
</script>

<style scoped lang="scss">
.imgDel{
  position: absolute;
  z-index: 4;
  top: 1px;
  border: 0;
  width: 15px!important;
  height: 15px!important;
  text-align: center;
  //right: -1px;
  left:64px;
  padding: 0px!important;
  line-height: 10px!important;
  border-radius: 0!important;
  font-weight:bold;
}
.img-box{
  position:absolute;
  z-index: 3;
  top:0;
  width: 80px;
  height: 80px;
  border:0;
}
.rich-content{
  width:99%;
  ::v-deep.el-form-item__content{
    margin-left:10px!important;
  }
}
</style>
